package com.astrofizzbizz.stoneedgegui.utilities;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.ChannelExec;

public class StoneEdgeIIITunnel 
{
	Session session = null;
    final static String host = "mail.stoneedgevineyard.com";
    final static String user = "remote";
    final static String domeCameraHostName = "axis";
    final static String finderCameraHostName = "axis1";
    final static String stoneEdgeGuiIIHostName = "localhost";
    final static String treffersWebHostName = "localhost";
    final static int domeCameraPort = 8082;
    final static int finderCameraPort = 8083;
    final static int stoneEdgeGuiIIPort = 8080;
    final static int treffersWebPort = 8081;
       
	public StoneEdgeIIITunnel(File privateKey) throws StoneEdgeIIIException 
	{
		JSch jsch=new JSch();
		if (session != null)
		{
			session.disconnect();
			session = null;
		}
		
	    try 
	    {
	        jsch.addIdentity(privateKey.getPath());
	    	session = jsch.getSession(user, host, 22);
	    } 
	    catch (JSchException e) 
	    {
	    	e.printStackTrace();
	    	throw new StoneEdgeIIIException("JSchException" + e.getMessage() );
	    
		}
	    
	    try 
	    {
	        java.util.Properties config = new java.util.Properties();
	        config.put("StrictHostKeyChecking", "no");
	        session.setConfig(config);
	        
	    	session.connect();
	    } 
	    catch (JSchException e) 
	    {
	    	throw new StoneEdgeIIIException("JSchException" + e.getMessage());
		}

	    setPortForwarding(stoneEdgeGuiIIPort, stoneEdgeGuiIIHostName, 8080);
	    setPortForwarding(treffersWebPort, treffersWebHostName, 80);
	    setPortForwarding(domeCameraPort, domeCameraHostName, 80);
	    setPortForwarding(finderCameraPort, finderCameraHostName, 80);
	    
	    System.out.println("Connected...");
	}
	public void setPortForwarding(int localPort, String host, int remotePort) throws StoneEdgeIIIException 
	{
	    try {session.setPortForwardingL(localPort, host, remotePort);} 
	    catch (JSchException e) 
	    {
	    	throw new StoneEdgeIIIException("Only one Tunnel per computer, Please!");
		}
	};
	public String[] executeCommand(String command, int bufferSize) throws StoneEdgeIIIException 
	{
	    Channel channel;
	    InputStream in;
		try {
			channel = session.openChannel("exec");
		    ((ChannelExec)channel).setCommand(command);
		    channel.setInputStream(null);
		    
		    ((ChannelExec)channel).setErrStream(System.err);
		    in=channel.getInputStream();
		    channel.connect();
		    String[] response = {"",""};
		    byte[] tmp=new byte[bufferSize];
		    while(true)
		    {
		    	while(in.available()>0)
		    	{
		    		int i=in.read(tmp, 0, bufferSize);
		    		if(i<0)break;
		    		response[0] = new String(tmp, 0, i);
		    	}
		    	if(channel.isClosed())
		    	{
		    		response[1] = new Integer(channel.getExitStatus()).toString();
		    		break;
		    	}
		        try{Thread.sleep(250);}catch(Exception ee){}
		    }
		    channel.disconnect();
		    return response;
		} catch (JSchException e) {
			e.printStackTrace();
	    	throw new StoneEdgeIIIException("JSchException");
		} catch (IOException e) {
			e.printStackTrace();
	    	throw new StoneEdgeIIIException("IOException");
		}
	}
	public void disconnect()
	{
		session.disconnect();
		session = null;
	}
	public static File privateKey() throws StoneEdgeIIIException
	{
		JFrame jframe = new JFrame("StoneEdge Tunnel");
        try 
        {
            UIManager.setLookAndFeel(
            UIManager.getCrossPlatformLookAndFeelClassName());
        } catch (Exception e) {}
        jframe.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
 		ClassLoader loader = Thread.currentThread().getContextClassLoader();
		String iconLoc = "com/astrofizzbizz/stoneedgegui/files/portal.jpg";
		URL resourceURL = loader.getResource(iconLoc);
		ImageIcon iconImage = new ImageIcon(resourceURL);
		jframe.setIconImage(iconImage.getImage());
        JLabel label1 = new JLabel(iconImage);
        JPanel panel1 = new JPanel();
        panel1.add(label1);
        jframe.getContentPane().add(panel1);
        jframe.pack();
        jframe.setVisible(true);
        // Get the size of the screen
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        
        // Determine the new location of the window
        int w = jframe.getSize().width;
        int h = jframe.getSize().height;
        int x = (dim.width-w)/2;
        int y = (dim.height-h)/2;
        
        // Move the window
        jframe.setLocation(x, y);
        
    	String delim = System.getProperty("file.separator");
    	String directoryPath = "." + delim;
    	File file = null;
    	JFileChooser fc = null;
		fc = new JFileChooser(directoryPath);
    	fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    	fc.setMultiSelectionEnabled(false);
    	fc.setSelectedFile(new File("StoneEdgeKey"));
        fc.setDialogTitle("Open StoneEdge Key");
        int returnVal = 0;
        returnVal = fc.showOpenDialog(jframe);
        if (returnVal == JFileChooser.APPROVE_OPTION) 
        {
            file = fc.getSelectedFile();
        } 
        
        jframe.dispose();
        if (file == null) throw new StoneEdgeIIIException("Invalid Key file");
		return file;
	}
	public static int getDomeCameraPort() {return domeCameraPort;}
	public static int getFinderCameraPort() {return finderCameraPort;}
	public static int getStoneCdgeguiiiPort() {return stoneEdgeGuiIIPort;}
	public static int getTreffersWebPort() {return treffersWebPort;}
	
	public static void main(String[] args) throws StoneEdgeIIIException 
	{
		File privateKey = StoneEdgeIIITunnel.privateKey();
	    new StoneEdgeIIITunnel(privateKey);	
	}

}
